package Projo;

import Database.AssessmentMgmt;
import Exception.CheckDataException;
import Exception.InsertionDataException;
import Exception.LoadDriverException;
import General.*;

public class ThreadBar extends Thread
{
	private volatile boolean running = true;
	private int cpt = 0, careImg = 0;
	private double pauseTimer = 0;
	private Student student;
	private int pauseFlag = 0, careFlag = 0, endFlag = 0, startFlag = 0, care = 3, end = 4;
	
	public ThreadBar(Student student)
	{
		this.student = student;
		this.student.getProgressBar().setValue(cpt); //Initialize the progressBar
	}
	
	public void run()
	{
		while(running == true)
		{
			try
			{
				sleep(student.getTime()); //Wait some time in millisecond
				cpt++;
				student.getProgressBar().setValue(cpt);			
				student.getProgressBar().repaint(); //Refresh the progressBar
				
				while(pauseFlag == 1) //While the pause is ON
				{
					sleep(100); //Wait a while
					pauseTimer++;
				}
	
				if(cpt == 50) //If the counter reach the middle of progressBar
				{
					if(careImg == 0) //If the image is not drawn
						student.setLogoStudent(care); //Draw of the image
					careFlag = 1; //Flag to 1
				}
					
				if(cpt == 100) //If the counter reach the end
					end(); //Stop the process
				System.out.println(cpt);
			}
			catch(InterruptedException | InsertionDataException | CheckDataException | LoadDriverException error) //If there is an error
			{
				TreatError.showError(error); //Show the error
			}
		}
		if(running == false) //If the process is stopped
			running = true; //Flag to true
	}
	
	public void end() throws InsertionDataException, CheckDataException, LoadDriverException
	{
		endFlag = 1; //Flag end to 1
		student.setLogoStudent(end); //Refresh logo
		running = false;
		student.getButtonPause().setEnabled(false);
		student.getButtonStart().setEnabled(false);
		student.getButtonStop().setEnabled(false);
		
		AssessmentMgmt asStopMgmt = new AssessmentMgmt(student.getConnection());
		asStopMgmt.endOfAssessment(GeneralInformation.getIdExaminationLaunch(), student.getID(), getPauseTimer());
	}
	
	//Gettors
	public int getCpt(){return cpt;}
	public int getPauseTimer(){return (int)(pauseTimer/10);}
	public int getPauseFlag(){return pauseFlag;}
	public int getCareFlag(){return careFlag;}
	public int getEndFlag(){return endFlag;}
	public int getStartFlag(){return startFlag;}
	public void setPauseFlag(int value){pauseFlag = value;}
	public void setStartFlag(int value){startFlag = value;}
	public void setEndFlag(int value){endFlag = value;}
}
